package com.zxm.web.controller.txcloud.face;

import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.ft.v20200304.FtClient;
import com.tencentcloudapi.ft.v20200304.models.*;
import com.zxm.common.core.domain.AjaxResult;
import com.zxm.common.core.domain.TxyFactory;
import com.zxm.common.core.domain.entity.TxyFaceChange;
import com.zxm.common.core.redis.RedisCache;
import com.zxm.common.exception.NeedPaidException;
import com.zxm.common.utils.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @Author silence.Z
 * @Date 2022/6/14 14:35
 * @PackageName:com.ruoyi.web.controller.txcloud.face
 * @ClassName: FaceChangeController
 * @Description: 人脸变换控制器
 * @Version 1.0
 */
@RestController
@RequestMapping("txcloud/face/facechange")
public class FaceChangeController {
	private static final Logger log = LoggerFactory.getLogger(FaceChangeController.class);
	@Autowired
	private RedisCache redisCache;

	@PreAuthorize("@ss.hasPermi('txcloud:face:facechange:list')")
	@PostMapping("changeAgePic")
	/**
	 * 人脸年龄变化
	 */
	public AjaxResult changeAgePic(@Validated @RequestBody TxyFaceChange faceChange) throws TencentCloudSDKException {
		//每月免费额度1000
		int num = ObjectUtils.isEmpty(redisCache.getCacheObject("changeAgePicNum")) ? 0 : Integer.parseInt(redisCache.getCacheObject("changeAgePicNum").toString());
		if (num >= 1000) {
			throw new NeedPaidException();
		}
		FtClient client = TxyFactory.createFace();
		ChangeAgePicRequest req = new ChangeAgePicRequest();
		if (StringUtils.isNotEmpty(faceChange.getImage())) {
			req.setImage(faceChange.getImage());
		}
		if (StringUtils.isNotEmpty(faceChange.getUrl())) {
			req.setUrl(faceChange.getUrl());
		}
		req.setRspImgType(faceChange.getRspImgType());
		req.setAgeInfos(faceChange.getAgeInfos());
		ChangeAgePicResponse resp = client.ChangeAgePic(req);
		//请求次数加1 设置过期时间为下月初减当前时间秒值
		LocalDateTime midnight = LocalDateTime.now().plusMonths(1).withDayOfMonth(1).withHour(0)
				.withMinute(0).withSecond(0).withNano(0);
		redisCache.setCacheObject("changeAgePicNum", ++num, Math.toIntExact(ChronoUnit.SECONDS.between(LocalDateTime.now(), midnight)), TimeUnit.SECONDS);
		// 输出json格式的字符串回包
		log.info(ChangeAgePicResponse.toJsonString(resp));
		return AjaxResult.success();
	}

	@PreAuthorize("@ss.hasPermi('txcloud:face:facechange:list')")
	@PostMapping("swapGenderPic")
	/**
	 * 性别转换
	 */
	public AjaxResult swapGenderPic(@Validated @RequestBody TxyFaceChange faceChange) throws TencentCloudSDKException {
		//每月免费额度1000
		int num = ObjectUtils.isEmpty(redisCache.getCacheObject("swapGenderPic")) ? 0 : Integer.parseInt(redisCache.getCacheObject("changeAgePicNum").toString());
		if (num >= 1000) {
			throw new NeedPaidException();
		}
		FtClient client = TxyFactory.createFace();
		SwapGenderPicRequest req = new SwapGenderPicRequest();
		if (StringUtils.isNotEmpty(faceChange.getImage())) {
			req.setImage(faceChange.getImage());
		}
		if (StringUtils.isNotEmpty(faceChange.getUrl())) {
			req.setUrl(faceChange.getUrl());
		}
		req.setRspImgType(faceChange.getRspImgType());
		req.setGenderInfos(faceChange.getGenderInfos());
		SwapGenderPicResponse resp = client.SwapGenderPic(req);
		//请求次数加1 设置过期时间为下月初减当前时间秒值
		LocalDateTime midnight = LocalDateTime.now().plusMonths(1).withDayOfMonth(1).withHour(0)
				.withMinute(0).withSecond(0).withNano(0);
		redisCache.setCacheObject("swapGenderPic", ++num, Math.toIntExact(ChronoUnit.SECONDS.between(LocalDateTime.now(), midnight)), TimeUnit.SECONDS);
		// 输出json格式的字符串回包
		log.info(SwapGenderPicResponse.toJsonString(resp));
		return AjaxResult.success(resp);
	}

	@PreAuthorize("@ss.hasPermi('txcloud:face:facechange:list')")
	@PostMapping("faceCartoonPic")
	/**
	 * 人像动漫化
	 */
	public AjaxResult faceCartoonPic(@Validated @RequestBody TxyFaceChange faceChange) throws TencentCloudSDKException {
		//每月免费额度1000
		int num = ObjectUtils.isEmpty(redisCache.getCacheObject("faceCartoonPic")) ? 0 : Integer.parseInt(redisCache.getCacheObject("changeAgePicNum").toString());
		if (num >= 1000) {
			throw new NeedPaidException();
		}
		FtClient client = TxyFactory.createFace();
		FaceCartoonPicRequest req = new FaceCartoonPicRequest();
		if (StringUtils.isNotEmpty(faceChange.getImage())) {
			req.setImage(faceChange.getImage());
		}
		if (StringUtils.isNotEmpty(faceChange.getUrl())) {
			req.setUrl(faceChange.getUrl());
		}
		if (StringUtils.isNotEmpty(faceChange.getDisableGlobalEffect())) {
			req.setDisableGlobalEffect(faceChange.getDisableGlobalEffect());
		}
		req.setRspImgType(faceChange.getRspImgType());
		FaceCartoonPicResponse resp = client.FaceCartoonPic(req);
		//请求次数加1 设置过期时间为下月初减当前时间秒值
		LocalDateTime midnight = LocalDateTime.now().plusMonths(1).withDayOfMonth(1).withHour(0)
				.withMinute(0).withSecond(0).withNano(0);
		redisCache.setCacheObject("faceCartoonPic", ++num, Math.toIntExact(ChronoUnit.SECONDS.between(LocalDateTime.now(), midnight)), TimeUnit.SECONDS);
		// 输出json格式的字符串回包
		log.info(FaceCartoonPicResponse.toJsonString(resp));
		return AjaxResult.success(resp);
	}

	@PreAuthorize("@ss.hasPermi('txcloud:face:facechange:list')")
	@PostMapping("morphFace")
	/**
	 * 人像渐变
	 */
	public AjaxResult morphFace(@Validated @RequestBody TxyFaceChange faceChange) throws TencentCloudSDKException {
		//每月免费额度1000
		int num = ObjectUtils.isEmpty(redisCache.getCacheObject("morphFace")) ? 0 : Integer.parseInt(redisCache.getCacheObject("changeAgePicNum").toString());
		if (num >= 1000) {
			throw new NeedPaidException();
		}
		FtClient client = TxyFactory.createFace();
		MorphFaceRequest req = new MorphFaceRequest();
		if (StringUtils.isNotEmpty(faceChange.getImages())) {
			req.setImages(faceChange.getImages());
		}
		if (StringUtils.isNotEmpty(faceChange.getUrls())) {
			req.setUrls(faceChange.getUrls());
		}
		if (StringUtils.isNotEmpty(faceChange.getGradientInfos())) {
			req.setGradientInfos(faceChange.getGradientInfos());
		}
		if (StringUtils.isNotEmpty(Collections.singleton(faceChange.getFps()))) {
			req.setFps(faceChange.getFps());
		}
		if (StringUtils.isNotEmpty(Collections.singleton(faceChange.getOutputWidth()))) {
			req.setOutputWidth(faceChange.getOutputWidth());
		}
		if (StringUtils.isNotEmpty(Collections.singleton(faceChange.getOutputHeight()))) {
			req.setOutputHeight(faceChange.getOutputHeight());
		}
		/*if (StringUtils.isNotEmpty(Collections.singleton(faceChange.getGradientInfos()))){
			req.setGradientInfos(faceChange.getGradientInfos());
		}*/
		MorphFaceResponse resp = client.MorphFace(req);
		//请求次数加1 设置过期时间为下月初减当前时间秒值
		LocalDateTime midnight = LocalDateTime.now().plusMonths(1).withDayOfMonth(1).withHour(0)
				.withMinute(0).withSecond(0).withNano(0);
		redisCache.setCacheObject("morphFace", ++num, Math.toIntExact(ChronoUnit.SECONDS.between(LocalDateTime.now(), midnight)), TimeUnit.SECONDS);
		// 输出json格式的字符串回包
		log.info(MorphFaceResponse.toJsonString(resp));
		return AjaxResult.success(resp);
	}

	@PreAuthorize("@ss.hasPermi('txcloud:face:facechange:list')")
	@GetMapping("queryFaceMorphJob")
	/**
	 * 查询人像渐变任务
	 */
	public AjaxResult queryFaceMorphJob(@RequestParam("jobId") String jobId) throws TencentCloudSDKException {
		//每月免费额度1000
		int num = ObjectUtils.isEmpty(redisCache.getCacheObject("queryFaceMorphJob")) ? 0 : Integer.parseInt(redisCache.getCacheObject("changeAgePicNum").toString());
		if (num >= 1000) {
			throw new NeedPaidException();
		}
		FtClient client = TxyFactory.createFace();
		QueryFaceMorphJobRequest req = new QueryFaceMorphJobRequest();
		req.setJobId(jobId);
		QueryFaceMorphJobResponse resp = client.QueryFaceMorphJob(req);
		//请求次数加1 设置过期时间为下月初减当前时间秒值
		LocalDateTime midnight = LocalDateTime.now().plusMonths(1).withDayOfMonth(1).withHour(0)
				.withMinute(0).withSecond(0).withNano(0);
		redisCache.setCacheObject("queryFaceMorphJob", ++num, Math.toIntExact(ChronoUnit.SECONDS.between(LocalDateTime.now(), midnight)), TimeUnit.SECONDS);
		// 输出json格式的字符串回包
		log.info(QueryFaceMorphJobResponse.toJsonString(resp));
		return AjaxResult.success(resp);
	}

	@PreAuthorize("@ss.hasPermi('txcloud:face:facechange:list')")
	@GetMapping("cancelFaceMorphJob")
	/**
	 * 撤销人像渐变任务
	 */
	public AjaxResult cancelFaceMorphJob(@RequestParam("jobId") String jobId) throws TencentCloudSDKException {
		//每月免费额度1000
		int num = ObjectUtils.isEmpty(redisCache.getCacheObject("cancelFaceMorphJob")) ? 0 : Integer.parseInt(redisCache.getCacheObject("changeAgePicNum").toString());
		if (num >= 1000) {
			throw new NeedPaidException();
		}
		FtClient client = TxyFactory.createFace();
		CancelFaceMorphJobRequest req = new CancelFaceMorphJobRequest();
		req.setJobId(jobId);
		CancelFaceMorphJobResponse resp = client.CancelFaceMorphJob(req);
		//请求次数加1 设置过期时间为下月初减当前时间秒值
		LocalDateTime midnight = LocalDateTime.now().plusMonths(1).withDayOfMonth(1).withHour(0)
				.withMinute(0).withSecond(0).withNano(0);
		redisCache.setCacheObject("cancelFaceMorphJob", ++num, Math.toIntExact(ChronoUnit.SECONDS.between(LocalDateTime.now(), midnight)), TimeUnit.SECONDS);
		log.info(CancelFaceMorphJobResponse.toJsonString(resp));
		return AjaxResult.success(resp);
	}
}
